package com.example.demotest.service;

import com.example.demotest.exception.UsernameAlreadyExistsException;
import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.pojo.User;
import com.example.demotest.pojo.dto.AdminDto;
import com.example.demotest.pojo.Admin;
import com.example.demotest.repository.AdminRepository;
import com.example.demotest.service.IAdminService;
import com.example.demotest.util.JWT;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AdminService implements IAdminService {

    @Autowired
    private AdminRepository adminRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseMessage<Admin> login(AdminDto adminDto) {
        Optional<Admin> adminOptional = findByAdminName(adminDto.getAdminName());

        if (adminOptional.isPresent()) {
            Admin admin = adminOptional.get();
            if (passwordEncoder.matches(adminDto.getPassword(), admin.getPassword())) {
                System.out.println("管理员登录成功");
                String token = JWT.generateAdminToken(admin.getAdminId()); // 关键：使用带 isAdmin 字段的 token
                return ResponseMessage.successWithToken(admin, token);
            }
        }

        return ResponseMessage.error(401, "管理员账号或密码错误");
    }

    private Optional<Admin> findByAdminName(String adminName) {
        return adminRepository.findByAdminName(adminName);
    }


    @Override
    public Admin register(AdminDto adminDto) {
        // 1. 检查管理员是否已存在
        if (adminRepository.findByAdminName(adminDto.getAdminName()).isPresent()) {
            throw new UsernameAlreadyExistsException("管理员用户名已存在");
        }

        // 2. 创建实体并拷贝属性
        Admin admin = new Admin();
        BeanUtils.copyProperties(adminDto, admin);

        // 3. 加密密码
        admin.setPassword(passwordEncoder.encode(adminDto.getPassword()));

        // 4. 保存管理员
        return adminRepository.save(admin);
    }

    @Override
    public void category(String categoryName) {

    }
}
